import axios,{AxiosInstance,InternalAxiosRequestConfig,AxiosError,AxiosResponse} from "axios";
import { ElNotification } from 'element-plus'
import router from '@/router/index'
import { useUserStore } from '@/store/auth'
import { 
    STORAGE_KEYS, 
    clearStorageItem, 
    ERROR_MESSAGES, 
    HTTP_STATUS, 
    NOTIFICATION_TYPES, 
    ROUTE_PATHS, 
    DELAY_TIMES 
} from '@/constants/auth'
const service:AxiosInstance=axios.create({
    baseURL:import.meta.env.VITE_API_URL, //后面我们会把它替换成环境变量
    timeout:5000,
    headers: {
        'Content-Type': 'application/json'
    }
});
//请求拦截器
service.interceptors.request.use((config:InternalAxiosRequestConfig)=>{
    // 不要覆盖已经设置的 Content-Type
    if (config.method === 'post' && config.data && !config.headers['Content-Type']) {
        config.headers['Content-Type'] = 'application/json';
    }
    
    // 自动添加X-Token到请求头
    const xToken = localStorage.getItem(STORAGE_KEYS.X_TOKEN);
    if (xToken) {
        config.headers['X-Token'] = xToken;
    }
    
    // 添加调试日志
    console.log('请求URL:', config.url);
    console.log('请求方法:', config.method);
    console.log('请求数据:', config.data);
    console.log('请求头:', config.headers);
    
    return config
},(error:AxiosError)=>{
    ElNotification({
        title: ERROR_MESSAGES.ERROR,
        message: error.message,
        type: NOTIFICATION_TYPES.ERROR,
    });
    return Promise.reject(error)
  }
)

//响应拦截器
service.interceptors.response.use((response:AxiosResponse)=>{
    if(response.data.code != HTTP_STATUS.SUCCESS){
        // 特殊处理401状态码 - 登录状态过期
        if(response.data.code === HTTP_STATUS.UNAUTHORIZED){
            ElNotification({
                title: ERROR_MESSAGES.LOGIN_EXPIRED,
                message: response.data.message || ERROR_MESSAGES.PLEASE_RELOGIN,
                type: NOTIFICATION_TYPES.WARNING,
                duration: DELAY_TIMES.NOTIFICATION_DURATION
            });
            
            // 清除用户状态
            const userStore = useUserStore();
            userStore.logout();
            
            // 清除本地存储的token
            clearStorageItem(STORAGE_KEYS.X_TOKEN);
            
            // 延迟跳转到登录页面，让用户看到提示信息
            setTimeout(() => {
                router.push(ROUTE_PATHS.LOGIN);
            }, DELAY_TIMES.LOGIN_REDIRECT);
            
            return Promise.reject(response.data);
        }
        
        // 其他错误码正常显示错误信息
        ElNotification({
            title: ERROR_MESSAGES.ERROR,
            message: response.data.message,
            type: NOTIFICATION_TYPES.ERROR,
        });
        return Promise.reject(response.data)
    }else{
        return response.data
    }
   
},(error:AxiosError)=>{
    // 处理网络错误或其他HTTP错误
    if(error.response?.status === HTTP_STATUS.UNAUTHORIZED){
        ElNotification({
            title: ERROR_MESSAGES.LOGIN_EXPIRED,
            message: ERROR_MESSAGES.PLEASE_RELOGIN,
            type: NOTIFICATION_TYPES.WARNING,
            duration: DELAY_TIMES.NOTIFICATION_DURATION
        });
        
        // 清除用户状态
        const userStore = useUserStore();
        userStore.logout();
        
        // 延迟跳转到登录页面
        setTimeout(() => {
            router.push(ROUTE_PATHS.LOGIN);
        }, DELAY_TIMES.LOGIN_REDIRECT);
        
        return Promise.reject(error);
    }
    
    ElNotification({
        title: ERROR_MESSAGES.ERROR,
        message: error.message,
        type: NOTIFICATION_TYPES.ERROR,
    });
    return Promise.reject(error)
})

export default service